package com.ruoyi.web.controller.ksdH5;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chuanglan.SMSConst;
import com.chuanglan.SmsCode;
import com.chuanglan.sms.util.ChuangLanSmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ArchMessage;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.service.IArchMessageService;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetMerchantService;

/**
 * 用户扫码注册
 * 
 * @author ruoyi
 * @date 2019-06-27
 */
@Controller		 
@RequestMapping("/clm")
public class RegisterH5Cardontroller {
	@Autowired
	IHatchetMerchantService merchantService;
	@Autowired
	IHatchetAgentService agentService;
	@Autowired
	IArchMessageService archMessageService;
	
	protected  Map<String, Object> SMS_POOL = new HashMap<String, Object>();
	/**
	 * 扫码注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/register")
	public String register(HttpServletRequest request, HttpServletResponse response,Model model) {
		String phone = request.getParameter("phone");
		String id = request.getParameter("id");
		String baseUrl = "http://47.105.206.25:8180/admin/";
		model.addAttribute("phone", phone);
		model.addAttribute("id", id);
		model.addAttribute("baseUrl", baseUrl);
		return "clm/register";
	}
	
	/**发送验证码
	 * 
	 * @param phone
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/sendSMS")
	public Map<String, Object> sendSMS(@RequestParam("phone") String phone) {
		Map<String, Object> results = new HashMap<String, Object>();
		try {
			HatchetMerchant merchant = merchantService.selectHatchetMerchantByPhone(phone);
			if (merchant != null) {
				results.put("apistatus", "300");
				return results;
			}
			String code = org.apache.commons.lang3.StringUtils.rightPad(RandomUtils.nextInt(0,999) + "", 3, "0")
					+ org.apache.commons.lang3.StringUtils.rightPad(RandomUtils.nextInt(0,999) + "", 3, "0");
			SMS_POOL.put(phone, new SmsCode(code, new Date().getTime()));
			
			String msg = java.lang.String.format(SMSConst.zhuce_sms, code);
			String errorMsg = ChuangLanSmsUtil.sendSMS(phone, msg);
			if (org.apache.commons.lang3.StringUtils.isNotBlank(errorMsg)) {
				results.put("apistatus", "100");
				results.put("error", errorMsg);
				results.put("apimsg", "");
				return results;
			} else {
				results.put("apistatus", "200");
				results.put("error", "");
				results.put("msg", "验证码发送成功");
				return results;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			results.put("msg", "数据连接失败，请联系客服！");
			return results;
		}
	}
	
	
	/**
	 * 注册
	 * @param merchant
	 * @param from
	 * @param validate
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping("/saveRegister")
	public Map<String, Object> saveRegister(String phone,String id,String parentPhone,String passwd,String validate) throws ParseException{
		Map<String, Object> results = new HashMap<String, Object>();
		System.out.println(phone+"-----"+id+"-----"+parentPhone+"-------"+passwd);
		HatchetMerchant merchant2 = merchantService.selectHatchetMerchantByPhone(phone);
		if (merchant2 != null) {
			results.put("status", "ZD");
			return results;
		}
		
		String merchantName = phone;
		//密码加密
		passwd = EncryptUtils.encryptMD5ToString(EncryptUtils.encryptMD5ToString(phone).toLowerCase()+EncryptUtils.encryptMD5ToString(passwd).toLowerCase()).toLowerCase();
		HatchetMerchant merchant = new HatchetMerchant();
		String productShort = "KSD";
		SmsCode code = (SmsCode)SMS_POOL.get(phone);
		long time = new Date().getTime();
		HatchetMerchant hms_parent = null;
		if (parentPhone != null && !"".equals(parentPhone)) {	
			//判断旧码用户还是新码用户
			if (parentPhone.contains("**")) {
				hms_parent = merchantService.selectHatchetMerchantById(id);
			} else {
				HatchetMerchant list  = merchantService.selectHatchetMerchantByPhone(parentPhone);
				if (list != null) {
					hms_parent = list;
				}else {
					results.put("status", "ZZ31");
					return results;
				}
			}
			if (hms_parent == null) {
				results.put("status", "ZZ31");
				return results;
			}
		} else {
			results.put("status", "ZZ32");
			return results;
		}
		try {
			if (StringUtils.isNotEmpty(validate)) {
				if (null != code && validate.equals(code.code) && (time - code.time < 600000)) {
					SMS_POOL.remove(phone);
				} else {
					results.put("status", "ZC");
					return results;
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		HatchetAgent ha = agentService.selectHatchetAgentById(hms_parent.getAgentId());
		String newuserid = StringUtils.randomUUID();
		merchant.setID(newuserid);
		merchant.setParentPhone(hms_parent.getPHONE());
		String merchantNo = getMerchantNo(phone);
		merchant.setMerchantNo(merchantNo);
		merchant.setPHONE(phone);
		merchant.setLinkPhone(phone);
		merchant.setPASSWD(passwd);
		merchant.setSTATUS("70A");
		merchant.setMerchantSource(hms_parent.getMerchantSource());
		merchant.setUpgradeCodeNum("0");
		// 去除毫秒
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strDate = sdf.format(new Date());
		Date date = sdf.parse(strDate);
		merchant.setCreateTime(date);
		if (ha != null) {
			merchant.setDepartmentCode(ha.getDepartmentCode());
			merchant.setCreateUserId(ha.getAgentUserId());
			merchant.setAgentId(ha.getID());
		}
		// 补充商户数据
		merchant.setUseStatus("10A");
		merchant.setAuthTrxType("SALE,QUERY");// ,REVERSAL 禁止撤销
		merchant.setAuthCardType("94B9B2CD07054AD8966908C1EB25863E,9CE762E65EFD4E70962680F60DF928B2");
		merchant.setSettleCycle(0); // 亿钱包注册的商户设置秒到
		merchant.setSettleStatus("0");
		merchant.setMaxFee(0);
		merchant.setProductShort(productShort);
		merchant.setWkRate(new BigDecimal("0.60"));// 快捷费率
		merchant.setRATE(new BigDecimal("0.45"));// 微信支付宝费率
		merchant.setYkRate("0.86+1");// 养卡费率
		merchant.setProcedureFee(new BigDecimal("1"));
		merchant.setLEVEL("1");// 默认注册是普通会员
		merchant.setIsTuiguang(1);// 0默认注册不是推广员 1推广
		merchant.setFreezeStatus("10A");
		merchant.setTotalMoney(new BigDecimal("0"));// 默认注册开始金额为0
		merchant.setConvertCount(0);
		merchant.setMerchantCnName(merchantName);
		merchant.setCAPITAL(new BigDecimal(0));
		try {
			//插入用户信息,刷关系
			ArchMessage archMessage = new ArchMessage();
			archMessage.setStatus(0);
			archMessage.setType("1");
			archMessage.setUserId(newuserid);
			archMessage.setBusiness(newuserid);
			archMessageService.save(archMessage);
			merchantService.insertHatchetMerchant(merchant);
			results.put("status", "00");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return results;
	}
	
	
	/**
	 * 生成商户编号后四位
	 */
	public String getMerchantNo(String phone) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMM");
		String randomNum = StringUtils.leftPad(RandomUtils.nextInt(0,9999) + "", 4, "0");
		String merchantNo = "220" + phone.subSequence(3, 7) + sdf.format(date) + randomNum;
		return merchantNo;
	}
	
	/**
	 * 扫码注册_跳转下载地址
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/jump")
	public String jump() {
		return "clm/jump";
	} 
	 
}